import java.util.concurrent.TimeUnit;

public class GuardedObject {

    private String data;

    private Object lock = new Object();

    public String getData() {
        synchronized (lock) {
            while (data == null) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            return data;
        }
    }

    public void sendData(String data) {
        synchronized (lock) {
            this.data = data;
            lock.notifyAll();
        }
    }

    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(() ->{
            String data = "666";
            System.out.println(Thread.currentThread().getName() + "生产数据 = " + data);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("发送数据");
            guardedObject.sendData(data);
        }, "t1").start();
        new Thread(() -> {
            String data = guardedObject.getData();
            System.out.println(Thread.currentThread().getName() + "接收到数据 = " + data);
        }, "t2").start();
    }
}
